import os
import re
import sys
#局限性太大了，使用图片的地方可能是放到数组中的，还有别的规则，不一定都是imagenamed
#查找所有图片
def find_png_jpg_files(directory):
    png_jpg_files = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.lower().endswith(('.png')):
                png_jpg_files.append(os.path.join(root, file))
    return png_jpg_files

def remove_at_symbol(image_filenames):
    cleaned_image_names = []
    for name in image_filenames:
        # name是名字不是路径
        # imgName = os.path.splitext(os.path.basename(name))[0]
        cleaned_name = name.split('@')[0]
        cleaned_image_names.append(cleaned_name)
    return cleaned_image_names

def remove_at_suffix(image_filenames):
    cleaned_image_names = []
    for name in image_filenames:
        cleaned_name = os.path.splitext(name)[0]
        cleaned_image_names.append(cleaned_name)
    return cleaned_image_names

def find_png_imagesets(directory):
    png_jpg_files = []
    for root, dirs, files in os.walk(directory):
        for file in dirs:
            if file.lower().endswith(('.imageset')):
                png_jpg_files.append(os.path.join(root, file))
    return png_jpg_files

#查找imageNamed引用的图片
def find_image_names_in_code(root_directory):
    image_names = set()
    #[UIImage imageNamed:@"图片"]
    # pattern = r'\[UIImage\s+imageNamed\s*?:\s*?@"(.*?)"\]'
    #@"图片"
    pattern = r'@"([^"]+)"'
    for root, dirs, files in os.walk(root_directory):
        for file in files:
            file_path = os.path.join(root, file)
            if file_path.endswith(('.m', '.mm', '.swift', '.xib', '.storyboard')):
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                    matches = re.findall(pattern, content)
                    image_names.update(matches)
    return image_names

def find_unused_images(used_image_names, image_files):
    unused_images = set()
    
    for image_file in image_files:
        image_name = os.path.basename(image_file)
        if image_name not in used_image_names:
            unused_images.add(image_name)
    
    return unused_images

def main():
    if len(sys.argv) != 2:
        print("Usage: python script_name.py <directory>")
        return
    
    directory = sys.argv[1]
    if not os.path.isdir(directory):
        print("错误：指定路径不存在或不是一个目录！")
        return
    
    image_files = find_png_imagesets(directory)
    image_names = [os.path.basename(image_file) for image_file in image_files]
    cleaned_image_names = remove_at_suffix(image_names)
    used_image_names = find_image_names_in_code(directory)
    unused_images = find_unused_images(used_image_names, cleaned_image_names)
    
    for name in unused_images:
        print(name)

#   /Users/srliu/Desktop/homework-repository/dx_ios_dev的副本/ios/UniversitySearch

    # print("未被使用的图片名称: ")
    # for name in unused_images:
    #     print(name)

if __name__ == "__main__":
    main()
